#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

//  封装一下错误退出的宏
#define ERR_EXIT(m) \
do \
{   \
    perror(m);  \
    exit(EXIT_FAILURE);  \
} while(0)

//  读取文件，写入命令管道
int main()
{
    //  1. 创建命名管道文件fifo
    int ret = mkfifo("fifo", 0664);
    if (ret < 0)
    {
        ERR_EXIT("mkfifo failed\n");
    }

    //  2. 以读方式打开待读文件abc
    int infd = open("abc", O_RDONLY);
    if (infd == -1)
        ERR_EXIT("open failed\n");

    //  3. 以写方式打开命名管道fifo
    int outfd;
    outfd = open("fifo", O_WRONLY);
    if (outfd == -1)
        ERR_EXIT("open falied\n");

    //  4.从待读文件中读取数据，写入管道文件中
    char buf[1024];
    int n;
    while((n = read(infd, buf, 1024)) > 0)
    {
        write(outfd, buf, n);
    }

    close(infd);
    close(outfd);
    return 0;
}